package gui;



import java.util.concurrent.Semaphore;

import world.Action;
import world.Map;
import world.Player;


public class Main {
	
	private static Map map = new Map(System.getProperty("user.dir")  + "/map2.txt");
	private static Main instance = null;

	static MainFrame mainFrame = new MainFrame();
	static SecondFrame secondFrame = new SecondFrame(mainFrame);
	static Semaphore blocker = new Semaphore(1);
	static private boolean pause = false;
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		/*Map m = new Map("C:\\Users\\S.B.King\\Documents\\Workspace Eclipse\\Wumpus\\map1.txt"); */
		boolean start = true;
		//boolean shot = false;
		int[] sensors = new int[5];
		Action a;
		Player p = new Player();
		
		mainFrame.setVisible(true);
		secondFrame.setVisible(true);
		
		while(start) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			getInstance().getTree().clear();	// czyszczenie drzewa wnioskowania
			
			sensors = p.sense(map.getField(p.getPosition()), map.isPlayerNearWall(), map.isWumpusDeathScreamEcho());
			p.tellKB(sensors);
			a = p.chooseAndPerformAction();
			
			//p.tellKB(a);
			if (a == Action.GRAB) {
				System.exit(0);
			}
			
			if (a == Action.SHOOT) {
				System.out.println("strzelam!!!");
			}
			
			//Update playera i mapy w kazdym przebiegu i wykrywanie przez playera sytuacji
			p = map.updateMap(a, p);

			// wyświetlanie
			getInstance().getTree().reload();
			mainFrame.reload();
			
			// czy pauza
			if (pause) {
				try {
					blocker.acquire();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}			
		}
	}
	
	
    /**
     * @return
     */
    public static Main getInstance() {
        if(instance == null) {
           instance = new Main();
        }
        return instance;
     }
	
	public Map getMap() {
		return map;
	}
	
	public Map createNewMap() {
		map = new Map(System.getProperty("user.dir")  + "/map1.txt");
		return map;
	}
	
	public Map createNewRandomMap() {
		map = new Map((int) Math.round(Math.random()*10 + 4));
		map.createRandomMap();
		return map;
	}
	
	public Tree getTree() {
		return secondFrame.getTree();
	}

	public void pauseSimulation() {
		pause = true;
	}
	
	public void continueSimulation() {
		if (pause) {
			pause = false;
			blocker.release();
		}
	}
	
	public void nextStep() {
		if (pause) {
			blocker.release();
		}
	}
	
	
	public MainFrame getMainFrame() {
		return mainFrame;
	}

}
